package com.gm.manager.common.exception;


import com.gm.manager.common.domian.PE;
import com.gm.manager.common.domian.RP;
import com.gm.manager.common.finalfiled.ResultCode;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ValidationException;
import java.util.List;

/**
 * @author zhuZhaoYang
 * @date 2021/7/11 22:33
 */
@RestControllerAdvice(value = {"com.gm"})
public class GlobalExceptionHandler {

    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public RP parameterExceptionHandler(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        if (bindingResult.hasErrors()) {
            List<ObjectError> allErrors = bindingResult.getAllErrors();
            if (allErrors.size() != 0) {
                FieldError objectError = (FieldError) allErrors.get(0);
                return new PE(objectError.getDefaultMessage());
            }
        }
        return new PE("error");
    }

    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(GmException.class)
    public RP parameterExceptionHandler2(GmException e) {
        return new PE(e.getResultCode(), e.getResultMessage());
    }

    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(ValidationException.class)
    public RP parameterValidationException(ValidationException e) {
        return new PE(ResultCode.PARAMETER_ERROR, e.getMessage());
    }


}
